<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Controller;
use App\Http\Controllers\ScoreRuleController;
use App\Models\BookHomeBanner;
use App\Models\BookHomeCollect;
use App\Models\HotSearch;
use App\Models\LibBook;
use App\Models\LibBookBarcode;
use App\Models\LibBookRecom;
use App\Models\LibBookType;
use App\Models\BookHomeOrder;
use App\Models\BookHomeOrderBook;
use App\Models\BookHomeSchoolbag;
use App\Models\BookHomeOrderAddress;
use App\Models\BookHomePostageSet;
use App\Models\BookHomePostalRev;
use App\Models\BookHomePurchase;
use App\Models\BookHomePurchaseSet;
use App\Models\BookHomeReadingList;
use App\Models\BookHomeReadingListBook;
use App\Models\BookTypes;
use App\Models\ShopBook;
use App\Models\UserAddress;
use App\Models\UserLibraryInfo;
use App\Models\UserWechatInfo;
use App\Validate\LibBookRecomValidate;
use Exception;
use Illuminate\Support\Facades\DB;


/**
 * 馆藏书线上借阅
 * Class LibraryBookRecom
 * @package app\port\controller
 */
class LibBookRecomController extends CommonController
{

    private $validate = null;
    private $libApi = null;
    private $model = null;
    private $libBookModel = null;
    private $score_type = 8;
    public function __construct()
    {
        parent::__construct();
        $this->validate = new LibBookRecomValidate();
        $this->libApi = $this->getLibApiObj();
        $this->model = new LibBookRecom();
        $this->libBookModel = new LibBook();
    }
    /**
     * 馆藏书类型筛选列表
     */
    public function bookTypeFiltrateList()
    {
        // $libBookTypeModelObj = new LibBookType();
        // $res = $libBookTypeModelObj->select('id', 'type_name', DB::raw("CHAR_LENGTH(type_name) as strlen_name"))
        //     ->where('is_del', 1)
        //     ->orderBy('strlen_name')
        //     ->get()
        //     ->toArray();
        // if ($res) {
        //     //增加一个“其他分类”
        //     $res[] = ['id' => 0, 'type_name' => '其他'];

        //     return $this->returnApi(200, '获取成功', true, $res);
        // }
        // $res = [['id' => 0, 'type_name' => '其他', 'strlen_name' => 2]]; //失败返回一个状态
        // return $this->returnApi(200, '获取成功', true, $res);
        // return $this->returnApi(203, '暂无数据');



        //获取中途分类法的书籍类型
        // $bookTypesObj = new BookTypes();
        // $page = $this->request->page ? intval($this->request->page) : 1;
        // $limit = $this->request->limit ? intval($this->request->limit) : 10;
        // $keywords = $this->request->keywords;
        // $condition[] = ['level', '=', 1];
        // if ($keywords) {
        //     $condition[] = ['type_name', 'like', "%$keywords%"];
        // }
        // return $bookTypesObj->getSimpleList(['id', 'title as type_name'], $condition, $page, $limit);




        //最新版 获取自定义分类
        $libBookTypeModelObj = new LibBookType();
        $res = $libBookTypeModelObj->getRecomBookType(999);
        if ($res) {
            //增加一个“其他分类”
            $res[] = ['id' => 0, 'type_name' => '其他'];

            return $this->returnApi(200, '获取成功', true, $res);
        }
        $res = [['id' => 0, 'type_name' => '其他']]; //失败返回一个状态
        return $this->returnApi(200, '获取成功', true, $res);
    }

    /**
     * 获取图书到家馆藏书数据（首页数据）
     */
    public function getBookHomeLibBookData()
    {
        $book_home_type = config('other.book_home_type');
        if (!in_array(2, $book_home_type)) {
            return $this->returnApi(201, '此功能暂未开放');
        }
        //获取banner
        $bookHomeBannerModel = new BookHomeBanner();
        $banner = $bookHomeBannerModel->lists([
            'type' => 2,
            'is_play' => 1,
            'limit' => 99,
        ]);
        $data['banner'] = $banner['data'] ?? [];
        //获取书单
        $bookHomeReadingListModel = new BookHomeReadingList();
        $reading_list = $bookHomeReadingListModel->getRecomReadingLibList(); //获取推荐的书单
        foreach ($reading_list['data'] as $key => &$val) {
            foreach ($val['con_reading_list_lib_book'] as $k => &$v) {
                $v['intro'] = strip_tags($v['intro']);
                unset($v['pivot']);
            }
        }
        $data['reading_list'] = $reading_list['data'] ?? [];
        //获取自定义分类
        $libBookTypeModel = new LibBookType();
        $data['book_type_data'] = $libBookTypeModel->getRecomBookType(); //获取推荐的书单
        //获取中图分类法分类
        $libBookRecomModel = new LibBookRecom();
        $data['classification_data'] = $libBookRecomModel->getClassificationData();

        if ($data) {
            return $this->returnApi(200, "获取成功", true, $data);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 书单列表（馆藏书）
     */
    public function readingListFiltrateList()
    {
        $page = intval($this->request->input('page', 1)) ?: 1;
        $limit = intval($this->request->input('limit', 10)) ?: 10;

        //获取书单
        $bookHomeReadingListModel = new BookHomeReadingList();
        $reading_list = $bookHomeReadingListModel->getRecomReadingLibList($limit); //获取推荐的书单
        foreach ($reading_list['data'] as $key => &$val) {
            foreach ($val['con_reading_list_lib_book'] as $k => &$v) {
                $v['intro'] = strip_tags($v['intro']);
                unset($v['pivot']);
            }
        }
        if ($reading_list['data']) {
            $reading_list = $this->disPageData($reading_list);
            return $this->returnApi(200, "获取成功", true, $reading_list);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 书单详情（馆藏书）
     *@param reading_id 书单id
     */
    public function readingListDetail()
    {
        // 自动验证
        if (!$this->validate->scene('reading_list_detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        //获取书单
        $bookHomeReadingListModel = new BookHomeReadingList();
        $res = $bookHomeReadingListModel->detail($this->request->reading_id); //获取推荐的书单
        if ($res) {
            return $this->returnApi(200, "获取成功", true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }
    /**
     * 书单书籍列表（馆藏书）
     * @param reading_id 书单id
     * @param page  页数 默认为 1
     * @param limit 每页条数 默认10
     */
    public function readingListBookList()
    {
        // 自动验证
        if (!$this->validate->scene('reading_list_book_list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        //获取书单
        $bookHomeReadingListBookModel = new BookHomeReadingListBook();
        $res = $bookHomeReadingListBookModel->lists($this->request->all()); //获取推荐的书单
        if ($res['data']) {
            $res = $this->disPageData($res);
            return $this->returnApi(200, "获取成功", true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     *获取所有的中图分类法
     */
    public function getClassification()
    {
        //获取中图分类法分类
        $libBookRecomModel = new LibBookRecom();
        $res = $libBookRecomModel->getClassificationData(0);
        if ($res) {
            return $this->returnApi(200, "获取成功", true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }


    /**
     * 馆藏书推荐列表（推荐书的接口）
     * @param token ：用户 token  可选
     * @param type_id 类型id  空表示全部 或不传
     * @param type_big_id 中图分类法id
     * @param page  页数 默认为 1
     * @param limit 每页条数 默认10
     *
     * @param keywords_type string 检索类型 all 任意词
     *                              title 书名
                                   author 作者
                                   classno 分类号
                                   isbn isbn号
                                   callno 索书号
     * @param keywords string 检索信息
     */
    public function getRecomList()
    {
        $keywords = $this->request->keywords;
        $keywords_type = $this->request->keywords_type;
        $type_id = request()->input('type_id', '');
        $type_big_id = request()->input('type_big_id', '');
        $page = intval(request()->input('page', 1)) ?: 1;
        $limit = intval(request()->input('limit', 10)) ?: 10;
        $user_id = $this->request->user_info['id'];

        //后面的id当metaid 使用
        $res = $this->model->lists(['id', 'metaid', 'metatable', 'book_name', 'author', 'isbn', 'press', 'pre_time', 'img', 'is_recom', 'access_number'], $type_id, $type_big_id, $keywords, $keywords_type, 1, null, $limit);
        // $res = $this->libApi->getBookInfo($keywords, null, null, $page, $limit, [$keywords_type], null, null, null, $type_id);
        // $res = $res['content'];
        // unset($res['content']);
        if ($res['data']) {
            foreach ($res['data'] as $key => $val) {
                $book_id = $this->libBookModel->where('metaid', $val['metaid'])->where('metatable', $val['metatable'])->value('id');

                //这里加了列表才能收藏，但是需要多次调用接口，接口流畅度会有问题
                if (empty($book_id)) {
                    $metatable = $val['metatable'];
                    $metaid = $val['metaid'];
                    $book_info = $this->libApi->getBookDetail($metatable, $metaid);
                    if ($book_info['code'] == 200) {
                        $bar_code_info = $this->libApi->getAssetPageInfoForOpac($metatable, $metaid);
                        if ($bar_code_info['code'] == 200) {
                            //有可能返回的数据里面，没有metatable值
                            if (empty($book_info['content']['metatable']) || $book_info['content']['metatable'] == 'null') {
                                $book_info['content']['metatable'] = $metatable;
                            }
                            $book_id = $this->libBookModel->getLibBookInfoId($book_info['content'], $bar_code_info['content']); //获取书籍id，并把条形码放在数据库中
                        }
                    }
                }
                $res['data'][$key]['id'] = $book_id; //重置成lib_book表id


                // if (empty($book_id)) {
                //     $res['data'][$key]['is_collect'] = false;
                //     //  $res['data'][$key]['is_schoolbag'] = false;
                // } else {
                //     if (empty($user_id)) {
                //         $res['data'][$key]['is_collect'] = false;
                //         $res['data'][$key]['is_schoolbag'] = false;
                //     } else {
                //         $isCollect = BookHomeCollect::isCollect($book_id, $user_id, 2);
                //         $res['data'][$key]['is_collect'] = empty($isCollect) ? false : true; //是否收藏

                //         //   $isSchoolbag = NewSchoolbagModel::isSchoolbag($val['id'], $user_id, 2);
                //         //   $res['data'][$key]['is_schoolbag'] = empty($isSchoolbag) ? false : true; //是否加入书袋
                //     }
                // }

                $res['data'][$key]['type_name'] = !empty($val['con_type']) ? $val['con_type']['type_name'] : '';
                unset($res['data'][$key]['con_type']);

                //获取书籍封面
                if ($val['access_number'] <= 5 && ($val['img'] == 'default/default_lib_book.png' || $val['img'] == '/default/default_lib_book.png' || empty($val['img']))) {
                    $controllerObj = new Controller();
                    $img = $controllerObj->getImgByIsbn($val['isbn']);
                    $change_img = [];
                    $change_img['access_number'] = $val['access_number'] + 1;
                    if ($img) {
                        $change_img['img'] = $img;
                    }
                    $this->model->where('id', $val['id'])->update($change_img);
                }
            }

            $res = $this->disPageData($res);
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }
    /**
     * 匹配馆藏书封面 （外部）
     */
    public function matchLibBookImg()
    {
        ini_set('max_execution_time', 60000); //秒为单位，自己根据需要定义
        ini_set('request_terminate_timeout', 60000); //秒为单位，自己根据需要定义
        ini_set('memory_limit', '1280M');
        $res = ShopBook::select('id', 'isbn')->Orwhere('img', 'default/default_lib_book.png')
            ->Orwhere('img', null)
            ->limit(148, 5000)
            ->get();
        foreach ($res as $key => $val) {
            // $commonObj = new \app\common\controller\Common();
            // $img = $commonObj->getImgByIsbn($val['isbn']);
            // if ($img !== false) {
            //     $val->img = $img;
            //     $val->save();//修改图片
            // }
            // sleep(10);
        }
    }


    /**
     * 馆藏书检索
     * @param keywords_type  检索条件   all 任意词
     *                              title 书名
                                    author 作者
                                    isbn isbn号
                                    callno 索书号
                                    classno 分类号
     *                              pubdate  出版年
     *                              publisher  出版社
     *                              subject  主题
     *                              ctrlno   控制号
     * @param keywords  检索内容
     * @param page  页数 默认为 1
     * @param limit 每页条数 默认10
     *
     *
     * @param type_id 类型id 按中图分类法来计算 （新增）
     */
    public function libBookList()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('lib_book_list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $keywords_type = request()->keywords_type ? request()->keywords_type : 'all';
        $keywords = addslashes(request()->keywords);
        $page = intval(request()->input('page', 1)) ?: 1;
        $limit = intval(request()->input('limit', 10)) ?: 10;

        $type_id = $this->request->type_id;

        $selectList = [$keywords_type];
        $occurList =  ["and"];

        //检索的馆藏地
        $curLocalList = BookHomePurchaseSet::where('type', 19)->value('content');
        if ($curLocalList) {
            $curLocalList = explode(',', $curLocalList);
        }
        $res = $this->libApi->getBookInfo($keywords, "score", "desc", $page, $limit, $selectList, $occurList, null, $curLocalList, $type_id);
        if ($res['code'] == 200) {
            //添加检索热词
            if (!empty($content)) {
                $hotSearchModel = new HotSearch();
                $hotSearchModel->hotSearchAdd($keywords, 2);
            }
            return $this->returnApi(200, '获取成功', true, $res['content']);
        }
        return $this->returnApi(203, '暂无数据');
    }
    /**
     * 获取馆藏书籍详情
     * @param recom_book_id 推荐书单的id
     * @param metaid 图书在图书馆的id
     * @param metatable 书目库
     */
    public  function getLibBookDetail()
    {
        //banner推荐时，用此参数获取数据
        if (!empty($this->request->recom_book_id)) {
            $recom_book_info = LibBookRecom::select('metaid', 'metatable')->where('id', $this->request->recom_book_id)->where('is_del', 1)->first();
            if (empty($recom_book_info)) {
                return $this->returnApi(201, '参数错误');
            }
            $metaid = $recom_book_info->metaid;
            $metatable = $recom_book_info->metatable;
        } else {
            //增加验证场景进行验证
            if (!$this->validate->scene('lib_book_detail')->check($this->request->all())) {
                return $this->returnApi(201,  $this->validate->getError());
            }

            $metaid = $this->request->metaid;
            $metatable = $this->request->metatable;
        }

        $user_id = $this->request->user_info['id'];

        $book_info = $this->libApi->getBookDetail($metatable, $metaid);
        //检索的馆藏地
        $curLocalList = BookHomePurchaseSet::where('type', 19)->value('content');
        if ($curLocalList) {
            $curLocalList = explode(',', $curLocalList);
        }

        $bar_code_info = $this->libApi->getAssetPageInfoForOpac($metatable, $metaid, $curLocalList);
        if ($book_info['code'] == 200) {
            //默认接口是不返回封面的
            //     $book_info['content']['img'] = $this->libBookModel->setImgAttr($book_info['content']['isbn']);
            //获取书籍封面
            if (isset($book_info['content']['access_number']) && $book_info['content']['access_number'] <= 5 && ($book_info['content']['img'] == 'default/default_lib_book.png' || $book_info['content']['img'] == '/default/default_lib_book.png' || empty($book_info['content']['img']))) {

                $controllerObj = new Controller();
                $img = $controllerObj->getImgByIsbn($book_info['content']['isbn']);
                $change_img = [];
                $change_img['access_number'] = $book_info['content']['access_number'] + 1;
                if ($img) {
                    $change_img['img'] = $img;
                    $book_info['content']['img'] = $img;
                }
                $this->libBookModel->where('id', $book_info['content']['id'])->update($change_img);
            }

            $book_id = 0;
            if ($bar_code_info['code'] == 200) {
                //有可能返回的数据里面，没有metatable值
                if (empty($book_info['content']['metatable']) || $book_info['content']['metatable'] == 'null') {
                    $book_info['content']['metatable'] = $metatable;
                }
                $book_id = $this->libBookModel->getLibBookInfoId($book_info['content'], $bar_code_info['content']); //获取书籍id，并把条形码放在数据库中
                //获取每一个条形码的状态
                foreach ($bar_code_info['content'] as $key => $val) {
                    $bar_code_info['content'][$key]['is_schoolbag'] =  false; //是否加入书袋
                }
            }

            $book_info['content']['id'] = (int)$book_id; //返回书籍在我们系统的id

            if (!empty($user_id)) {
                // dump($book_id);die;
                if (empty($book_id)) {
                    $book_info['content']['is_collect'] = false; //未收藏
                    // $data['is_schoolbag'] =  false;//未加入书袋
                    $book_info['content']['schoolbag_number'] =  0; //书袋数量
                } else {
                    $isCollect = BookHomeCollect::isCollect($book_id, $user_id, 2);
                    $book_info['content']['is_collect'] = empty($isCollect) ? false : true; //是否收藏
                    $libBookBarcodeModelObj = new LibBookBarcode();

                    //获取每一个条形码的状态
                    foreach ($bar_code_info['content'] as $key => $val) {
                        $barcode_id = $libBookBarcodeModelObj->getBarCodeId($book_id, $val['barcode'], $val['metatable'], $val['metaid']);

                        $isSchoolbag = BookHomeSchoolbag::isSchoolbag($book_id, $user_id, 2, $barcode_id);
                        $bar_code_info['content'][$key]['is_schoolbag'] = empty($isSchoolbag) ? false : true; //是否加入书袋
                        $bar_code_info['content'][$key]['barcode_id'] = $barcode_id; //条形码id
                    }
                    //书袋书籍数量
                    $book_info['content']['schoolbag_number'] = BookHomeSchoolbag::where('user_id', $book_id)
                        ->where('type', 2)
                        ->count();
                }
            } else {
                $book_info['content']['is_collect'] = false; //未收藏
                // $data['is_schoolbag'] =  false;//未加入书袋
                $book_info['content']['schoolbag_number'] =  0; //书袋数量
            }

            //判断是否收藏 和 是否加入购物车
            if ($bar_code_info['code'] == 200) {
                $book_info['content']['bar_code_info'] = $bar_code_info['content'];
            } else {
                $book_info['content']['bar_code_info'] = null;
            }
            $book_info['content']['intros'] = strip_tags($book_info['content']['intro']);
            $book_info['content']['price'] = str_replace('CNY', '', $book_info['content']['price']);
            // if (!empty($book_info['content']['classno'])) {
            //     $classify = substr($book_info['content']['classno'], 0, 1);
            //     $type_name = BookTypes::where('classify', $classify)->value('title');
            //     $book_info['content']['type_name'] = $type_name ? $type_name : '暂无分类';
            // } else {
            //     $book_info['content']['type_name'] = '暂无分类';
            // }


            if (!empty($book_info['content']['type_id'])) {
                $type_name = BookTypes::where('id', $book_info['content']['type_id'])->value('title');
                $book_info['content']['type_name'] = $type_name ? $type_name : '暂无分类';
            } else {
                $book_info['content']['type_name'] = '暂无分类';
            }

            return $this->returnApi(200, '', true, $book_info['content']);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 我的馆藏书收藏列表
     * @param token ：用户 token
     * @param page  页数，默认为1，
     * @param limit  条数，默认显示 10条
     */
    public function myLibraryBookCollectList()
    {
        $user_id = $this->request->user_info['id'];
        $page = intval($this->request->input('page', 1)) ?: 1;
        $limit = intval($this->request->input('limit', 10)) ?: 10;

        $res = BookHomeCollect::select('id', 'book_id', 'create_time')
            ->with(['libBookCollect' => function ($query) {
                $query->select('id', 'book_name', 'author', 'press', 'pre_time', 'isbn', 'price', 'img', 'intro', 'metaid', 'metatable');
            }])
            // ->whereHas('libBookCollect', function ($query) {
            //     $query->where('is_del', 1);
            // })
            ->where('user_id', $user_id)
            ->where('type', 2)
            ->orderByDesc('id')
            ->paginate($limit)
            ->toArray();
        foreach ($res['data'] as &$val) {
            $val['book_name'] = $val['lib_book_collect']['book_name'];
            $val['author'] = $val['lib_book_collect']['author'];
            $val['press'] = $val['lib_book_collect']['press'];
            $val['pre_time'] = $val['lib_book_collect']['pre_time'];
            $val['isbn'] = $val['lib_book_collect']['isbn'];
            $val['price'] = $val['lib_book_collect']['price'];
            $val['img'] = $val['lib_book_collect']['img'];
            $val['intro'] = $val['lib_book_collect']['intro'];
            $val['metaid'] = $val['lib_book_collect']['metaid'];
            $val['metatable'] = $val['lib_book_collect']['metatable'];

            unset($val['id']);
            unset($val['lib_book_collect']);
        }

        if (!empty($res['data'])) {
            $res = $this->disPageData($res);
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 馆藏书加入书袋与移出书袋
     * @param  token ：用户 token
     * @param  $book_id 书籍id
     * @param  $barcode_id 条形码id
     */
    public function LibBookSchoolbag()
    {
        // 自动验证
        if (!$this->validate->scene('lib_book_schoolbag')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $book_id = $this->request->book_id;
        $barcode_id = $this->request->barcode_id;
        $user_id = $this->request->user_info['id'];
        $res = BookHomeSchoolbag::isSchoolbag($book_id, $user_id, 2, $barcode_id);
        if (empty($res)) {
            //加入书袋，书袋数量不能超过 100 个
            $count = BookHomeSchoolbag::where('user_id', $user_id)
                ->where('type', 2)
                ->count();
            if ($count >= 100) {
                return $this->returnApi(202, '加入失败，书袋书籍不能超过100本');
            }
            $bookHomeSchoolbag = new BookHomeSchoolbag();
            $result = $bookHomeSchoolbag->add([
                'user_id' => $user_id,
                'book_id' => $book_id,
                'barcode_id' => $barcode_id,
                'type' => 2,
            ]);
            $msg = '加入书袋';
        } else {
            $result = $res->delete();
            $msg = '移出书袋';
        }
        if ($result) {
            return $this->returnApi(200, $msg . '成功', true);
        }
        return $this->returnApi(202, $msg . '失败');
    }

    /**
     * 我的馆藏书书袋列表
     * @param token ：用户 token
     * @param page  页数，默认为1，
     * @param limit  条数，默认显示 10条
     */
    public function myLibBookSchoolbagList()
    {
        $user_id = $this->request->user_info['id'];
        $page = intval($this->request->input('page', 1)) ?: 1;
        $limit = intval($this->request->input('limit', 10)) ?: 10;
        $newSchoolbag = new BookHomeSchoolbag();
        $data = $newSchoolbag->myLibBookSchoolbagList($user_id, $limit);

        if (!empty($data)) {
            $data = $this->disPageData($data);
            return $this->returnApi(200, '获取成功', true, $data);
        }
        return $this->returnApi(203, '暂无数据');
    }


    /**
     * 获取订单预估金额
     * @param  token ：用户 token
     * @param  $barcode_ids  条形码id 多本书用 ， 逗号 拼接
     */
    public function getOrderForecastPrice()
    {
        // 自动验证
        if (!$this->validate->scene('get_order_forecast_price')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $user_id = $this->request->user_info['id'];
        $account_id = $this->request->user_info['account_id'];
        $barcode_ids = $this->request->barcode_ids;
        $barcode_ids = explode(',', $barcode_ids);

        //验证密码是否正确
        $userLibraryInfoModel = new UserLibraryInfo();
        $account_info = $userLibraryInfoModel->checkAccountPwdIsNormal($user_id);
        if (is_string($account_info)) {
            return $this->returnApi(204, $account_info);
        }
        DB::beginTransaction();
        try {
            $bookHomeOrderModel = new BookHomeOrder();
            //获取邮费价格
            $postage_price = BookHomePostageSet::where('type', 2)
                ->where('number', count($barcode_ids))
                ->value('price');
            if (empty($postage_price)) {
                throw new \Exception('后台邮费设置不正确，请联系管理员处理');
            }

            $postageBudget = $bookHomeOrderModel->getPostageBudget($postage_price, $account_id);  //需要自己支付邮费

            $dis_price = $postageBudget ? 0 : $postage_price; //0 表示不支付 //图书馆支付邮费

            DB::commit();
            return $this->returnApi(200, '获取成功', true, [
                'dis_price' => $dis_price, //预估金额
                'price' => $postage_price, //实际金额
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 获取 馆藏书 预支付订单信息
     * @param  token ：用户 token
     * @param  $barcode_ids  条形码id 多本书用 ， 逗号 拼接
     * @param  $address_id 收货地址id
     */
    public function getOrderInfo()
    {
        // 自动验证
        if (!$this->validate->scene('get_order_info')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $user_id = $this->request->user_info['id'];
        $account_id = $this->request->user_info['account_id'];


        //判断读者证号密码是否正确
        $userLibraryInfoModel = new UserLibraryInfo();
        $account_lib_info = $userLibraryInfoModel->checkAccountPwdIsNormal($user_id);
        if (is_string($account_lib_info)) {
            return $this->returnApi(204, $account_lib_info);
        }

        $barcode_ids = array_filter(array_unique(explode(',', $this->request->barcode_ids)));
        DB::beginTransaction();
        try {
            /*if(!$this->checkScore(request()->score,$this->score_type , count($barcode_ids))){
                throw new \Exception('积分不足无法使用此功能');
            }*/
            //判断用户积分是否满足要求
            $scoreRuleObj = new ScoreRuleController();
            $score_status = $scoreRuleObj->checkScoreStatus(8, $user_id, $account_id);
            if ($score_status['code'] == 202 || $score_status['code'] == 203) {
                throw new Exception($score_status['msg']);
            }

            $bookHomeOrderModel = new BookHomeOrder();
            $bookHomeOrderBookModel = new BookHomeOrderBook();
            //判断用户借阅权限
            $barcode_info_arr = [];

            //检索的馆藏地
            $curLocalList = BookHomePurchaseSet::where('type', 19)->value('content');
            if ($curLocalList) {
                $curLocalList = explode(',', $curLocalList);
            }

            foreach ($barcode_ids as $key => $val) {
                $barcode_info = LibBookBarcode::where('id', $val)->first();
                //限制不允许采购的书籍
                if (!empty($curLocalList) && !in_array($barcode_info['cur_local'], $curLocalList)) {
                    throw new Exception('条形码：【' . $barcode_info['barcode'] . '】不符合采购要求');
                }

                if (empty($barcode_info)) {
                    throw new Exception('网络错误，请联系管理员处理');
                }
                $barcode_info_arr[] = $barcode_info;
            }

            //判断馆藏书借阅权限
            $this->libBookModel->checkNewBookBorrowAuth($this->request->user_info, $barcode_info_arr);

            $order_number = get_order_id();
            //获取邮费价格
            $postage_price = BookHomePostageSet::where('type', 2)
                ->where('number', count($barcode_ids))
                ->value('price');
            if (empty($postage_price)) {
                throw new Exception('后台邮费设置不正确，请联系管理员处理');
            }

            $postageBudget = $bookHomeOrderModel->getPostageBudget($postage_price, $account_id);

            if ($postageBudget) {
                //图书馆支付邮费
                $dis_price = 0;
                $discount = 0; //表示不支付
                $is_pay = 2; //直接支付成功
                $payment = 2; //图书馆邮费支付
                $change_time = date('Y-m-d H:i:s'); //支付时间
                $msg = '申请提交成功,等待后台管理员审核，本单邮费由图书馆统一支付！';
            } else {
                //需要自己支付邮费
                $dis_price = $postage_price;
                $discount = 100; //表示全额支付
                $is_pay = 1; //表示全额支付
                $payment = 1; //微信支付
                $change_time = null; //支付时间
                $msg = '下订单成功';
            }

            //添加馆藏书订单表
            $create_time = date('Y-m-d H:i:s');
            $bookHomeOrderModel->add([
                'order_number' => $order_number,
                'user_id' => $user_id,
                'account_id' => $account_id,
                'price' => $postage_price,
                'dis_price' => $dis_price,
                'discount' => $discount,
                'is_pay' => $is_pay,
                'payment' => $payment,
                'create_time' => $create_time,
                'expire_time' => date('Y-m-d H:i:s', strtotime("+30 minute", strtotime($create_time))), //订单过期时间，默认30分钟
                'change_time' => $change_time,
                'type' => 2,
            ]);

            //添加订单地址
            $address_info = UserAddress::find($this->request->address_id);
            $bookHomeOrderAddressModel = new BookHomeOrderAddress();
            $bookHomeOrderAddressModel->add([
                'order_id' => $bookHomeOrderModel->id,
                'username' => $address_info['username'],
                'tel' => $address_info['tel'],
                'province' => $address_info['province'],
                'city' => $address_info['city'],
                'district' => $address_info['district'],
                'street' => $address_info['street'],
                'address' => $address_info['address']
            ]);

            //添加馆藏书订单书籍表
            $order_book = [];
            foreach ($barcode_info_arr as $v) {
                $order_book[] = [
                    'order_id' => $bookHomeOrderModel->id,
                    'book_id' => $v['book_id'],
                    'barcode_id' => $v['id'],
                    'type' => 2,
                    'create_time' => date('Y-m-d H:i:s'),
                ];
            }
            $bookHomeOrderBookModel->insert($order_book);

            if ($postageBudget) {
                //添加推送模板消息
                // $tempInfoObj = new \app\common\controller\TempInfo();
                // $data['openid'] = \app\common\controller\Common::getOpenIdByUserId(self::$param['user_id']);
                // $data['username'] = UserLibraryInfoModel::where('id' , $account_id)->value('username');
                // $data['msg'] = '在线借阅';
                // $data['msg1'] = '馆藏书';
                // $data['msg2'] = '请随时关注审核进度！';
                // $data['create_time'] = $change_time;
                // $data['link'] = '?booktype=2&id='.$bookHomeOrderModel->id;
                // $tempInfoObj->sendTempInfoApplySuccess($data);

                $this->systemAdd('书籍采购提交成功', $user_id, $account_id, 37, $bookHomeOrderModel->id, '书籍采购提交成功，等待后台管理员审核，请随时关注审核进度！');
            }

            DB::commit();
            return $this->returnApi(200, $msg, true, [
                'order_id' => $bookHomeOrderModel->id,
                'order_number' => $order_number,
                'create_time' => $create_time,
                'price' => $postage_price,
                'postage_budget' => $postageBudget
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }
    /**
     * 我的 馆藏书 订单列表
     * @param token ：用户 token
     * @param $page  页数，默认为1，
     * @param $limit  条数，默认显示 10条
     */
    public function myOrderList()
    {
        //处理已失效的订单
        BookHomeOrder::checkNoPayOrder();

        $user_id = $this->request->user_info['id'];
        $page = intval($this->request->input('page', 1)) ?: 1;
        $limit = intval($this->request->input('limit', 10)) ?: 10;

        //判断读者证号密码是否正确
        $userLibraryInfoModel = new UserLibraryInfo();
        $account_lib_info = $userLibraryInfoModel->checkAccountPwdIsNormal($user_id);
        if (is_string($account_lib_info)) {
            return $this->returnApi(204, $account_lib_info);
        }

        $bookHomeOrderModel = new BookHomeOrder();
        $libBookBarcodeModel = new LibBookBarcode();
        $libBookBarcodeTable = $libBookBarcodeModel->getTable();
        $res = $bookHomeOrderModel->select('id', 'order_number', 'price', 'is_pay', 'create_time', 'change_time', 'refund_time', 'agree_time', 'deliver_time')
            ->with(['getLibOrderBookInfo' => function ($query) {
                $query->select($this->libBookModel->getTable() . '.id as book_id', 'book_name', 'author', 'press', 'isbn', 'img', 'metaid', 'metatable');
            }, 'getLibBarcodeInfo' => function ($query) use ($libBookBarcodeTable) {
                $query->select($libBookBarcodeTable . '.id as barcode_id', $libBookBarcodeTable . '.book_id', 'barcode');
            }])
            ->where('account_id', $account_lib_info['id'])
            ->where('type', 2)
            ->orderByDesc('id')
            ->paginate($limit)
            ->toArray();

        //组装数据
        foreach ($res['data'] as $key => $val) {
            foreach ($val['get_lib_order_book_info'] as $ke => $va) {
                $res['data'][$key]['get_order_book_info'][$ke]['id'] = $va['book_id'];
                $res['data'][$key]['get_order_book_info'][$ke]['book_name'] = $va['book_name'];
                $res['data'][$key]['get_order_book_info'][$ke]['author'] = $va['author'];
                $res['data'][$key]['get_order_book_info'][$ke]['press'] = $va['press'];
                $res['data'][$key]['get_order_book_info'][$ke]['isbn'] = $va['isbn'];
                $res['data'][$key]['get_order_book_info'][$ke]['img'] = $va['img'];
                $res['data'][$key]['get_order_book_info'][$ke]['metaid'] = $va['metaid'];
                $res['data'][$key]['get_order_book_info'][$ke]['metatable'] = $va['metatable'];
                $res['data'][$key]['get_order_book_info'][$ke]['barcode'] = '未知'; //防止前台出错
                foreach ($val['get_lib_barcode_info'] as $k => $v) {
                    if ($v['book_id'] == $va['book_id']) {
                        $res['data'][$key]['get_order_book_info'][$ke]['barcode'] = $v['barcode'];
                        break;
                    }
                }
            }
            unset($res['data'][$key]['get_lib_order_book_info']);
            unset($res['data'][$key]['get_lib_barcode_info']);
        }
        if ($res['data']) {
            $res = $this->disPageData($res);
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }
    /**
     * 我的馆藏书订单详情
     * @param token ：用户 token
     * @param $order_id ：订单id
     */
    public function myOrderDetail()
    {
        if (!$this->validate->scene('my_order_detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $user_id = $this->request->user_info['id'];
        $order_id = $this->request->order_id;

        //判断读者证号密码是否正确
        $userLibraryInfoModel = new UserLibraryInfo();
        $account_lib_info = $userLibraryInfoModel->checkAccountPwdIsNormal($user_id);
        if (is_string($account_lib_info)) {
            return $this->returnApi(204, $account_lib_info);
        }

        $bookHomeOrderModel = new BookHomeOrder();

        //查看当前订单是否失效
        // $this->checkOrderState($bookHomeOrderModel, $order_id);

        //查看当前订单是否失效
        BookHomeOrder::checkNoPayOrder($order_id);
        $libBookBarcodeModel = new LibBookBarcode();
        $libBookBarcodeTable = $libBookBarcodeModel->getTable();
        $bookHomeOrderAddressModel = new BookHomeOrderAddress();
        $bookHomeOrderAddressTable = $bookHomeOrderAddressModel->getTable();
        $res = $bookHomeOrderModel->select('id', 'order_number', 'tracking_number', 'price', 'dis_price', 'is_pay', 'payment', 'create_time', 'change_time', 'refund_time', 'agree_time', 'deliver_time', 'cancel_time', 'cancel_remark', 'refund_remark')
            ->with(['getOrderAddress' => function ($query) use ($bookHomeOrderAddressTable) {
                $query->select($bookHomeOrderAddressTable . '.id', 'order_id', 'username', 'tel', 'province', 'city', 'district', 'street', 'address');
            }, 'getLibOrderBookInfo' => function ($query) {
                $query->select($this->libBookModel->getTable() . '.id as book_id', 'book_name', 'author', 'press', 'pre_time', 'img', 'isbn', 'price', 'metaid', 'metatable');
            }, 'getLibBarcodeInfo' => function ($query) use ($libBookBarcodeTable) {
                $query->select($libBookBarcodeTable . '.id as barcode_id', $libBookBarcodeTable . '.book_id', 'barcode');
            }])
            ->where('account_id', $account_lib_info['id'])
            ->where('id', $order_id)
            ->first();

        if ($res) {
            $res = $res->toArray();
            $res['create_time'] = date('Y-m-d H:i:s', strtotime($res['create_time']));

            //组装数据
            foreach ($res['get_lib_order_book_info'] as $ke => $va) {
                $res['get_order_book_info'][$ke]['id'] = $va['book_id'];
                $res['get_order_book_info'][$ke]['book_name'] = $va['book_name'];
                $res['get_order_book_info'][$ke]['author'] = $va['author'];
                $res['get_order_book_info'][$ke]['press'] = $va['press'];
                $res['get_order_book_info'][$ke]['isbn'] = $va['isbn'];
                $res['get_order_book_info'][$ke]['img'] = $va['img'];
                $res['get_order_book_info'][$ke]['metaid'] = $va['metaid'];
                $res['get_order_book_info'][$ke]['metatable'] = $va['metatable'];
                $res['get_order_book_info'][$ke]['barcode'] = '未知'; //防止前台出错
                foreach ($res['get_lib_barcode_info'] as $k => $v) {
                    if ($v['book_id'] == $va['book_id']) {
                        $res['get_order_book_info'][$ke]['barcode'] = $v['barcode'];
                        break;
                    }
                }
            }

            unset($res['get_lib_order_book_info']);
            unset($res['get_lib_barcode_info']);

            //获取运单轨迹
            if (!empty($res['tracking_number'])) {
                $bookHomePostalRevModelObj = new BookHomePostalRev();
                $res['track'] = $bookHomePostalRevModelObj->getTrack($res['tracking_number']);
            } else {
                $res['track'] = null;
            }

            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 馆藏书续借功能  (统一使用 LibInfo 下的续借接口)
     * @param barcode 条形码
     * @param book_name 书名
     * @param author 作者
     *
     * json  格式数据  [['book_name'=>1,'barcode'=>11,'author'=>1],['book_name'=>1,'barcode'=>11,'author'=>1]]
     */
    public function _bookRenew()
    {
        if (!$this->validate->scene('book_renew')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $content = json_decode($this->request->content, true);
        dump($content);
        die;
        $msg = '';
        foreach ($content as $key => $val) {
            $result = BookHomePurchase::where('barcode', $val['barcode'])->where('return_state', 'neq', 2)->first();
            if (!empty($result) && $result['node'] == 2) {
                // return $this->returnApi(202 , '此记录不支持续借');
                $msg .= '【' . $val['book_name'] . '】此书不支持续借；';
                continue;
            }

            $libApi = $this->getLibApiObj();
            $res = $libApi->renewBook($val['barcode']);

            if ($res['code'] !== 200) {
                $msg .= '【' . $val['book_name'] . '】' . $res['msg'] . ' '; //$res['msg'] 自带一个分号
                continue;
                // return $this->returnApi(202 , $res['msg']);
            }
            //获取正在借阅中的数据，增加应归还时间
            if ($result) {
                $result->expire_time = $res['content']['returnDate']; //增加应归还时间
                $result->save();
            }

            //添加系统消息
            if ($res['code'] === 200) {
                $this->systemAdd('续借成功', $result['user_id'], $result['account_id'], 38, null, '【' . $val['book_name'] . '】,续借成功！');

                //添加推送模板消息
                if (config('other.is_send_wechat_temp_info')) {
                    $tempInfoObj = new \App\Http\Controllers\TempInfoController();
                    $data['openid'] = UserWechatInfo::getOpenIdByUserId(request()->user_info['id']);
                    $data['msg'] = '续借成功，请在规定时间内归还！';

                    // if($result['type'] == 1){
                    //     $book_info = ShopBook::where('id' , $result['book_id'])->first();
                    // }else{
                    //     $book_info = LibBook::where('id' , $result['book_id'])->first();
                    // }
                    $data['book_name'] = $val['book_name'];
                    $data['author'] = $val['author'];
                    $data['return_time'] = $res['content']['returnDate'];
                    $data['number'] = !empty($res['content']['renew']) ? $res['content']['renew'] : (!empty($res['content']['renewNum']) ? $res['content']['renewNum'] : 1);
                    $tempInfoObj->sendTempInfoRenewSuccess($data);
                }
            }
        }

        return $this->returnApi(200, $msg ? $msg : "续借成功", true);
    }

    /**
     * @param $bookHomeOrderModel
     * @param $order_id
     */
    // public function checkOrderState($bookHomeOrderModel, $order_id)
    // {
    //     $order_info = $bookHomeOrderModel->field('id,create_time')->where('is_pay', 1)->where('id', $order_id)->first();
    //     $change_time = date('Y-m-d H:i:s', strtotime("+30 minute", strtotime($order_info['create_time'])));
    //     if ($change_time <= date('Y-m-d H:i:s')) {
    //         $bookHomeOrderModel->where('id', $order_info['id'])->update([
    //             'is_pay' => 4,
    //             'change_time' => $change_time,
    //         ]);
    //         $bookHomeOrderBookModel = new BookHomeOrderBook();
    //         $book_id_all = $bookHomeOrderBookModel->where('order_id', $order_info['id'])->pluck('book_id');
    //         //增加库存
    //         if ($order_info['type'] == 1) {
    //             foreach ($book_id_all as $v) {
    //                 $res = ShopBook::modifyRepertoryNumber($v, 1);
    //                 if ($res !== true) {
    //                     throw new \Exception($res);
    //                 }
    //             }
    //         }
    //     }
    // }







}
